import {defineStore} from "pinia";
import {login, logout, getUserInfo} from "@/api/login";
import {LoginUser} from "@/common/interface/login.ts";
import defaultAvatar from "@/assets/logo.png";


const user = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token'),
        name: '',
        avatar: '',
        roles: [] as any,
        permissions: []
    }),
    actions: {
        //登录
        Login(loginForm: LoginUser) {
            return new Promise<void>((resolve, reject) => {
                login(loginForm).then((res: any) => {
                    localStorage.setItem('token', res.token);
                    this.token = res.token;
                    resolve();
                }).catch((error: any) => {
                    reject(error);
                })
            })
        },

        //获取用户信息
        GetUserInfo() {
            return new Promise<void>((resolve, reject) => {
                getUserInfo().then((res: any) => {
                    const user = res.user
                    const avatar = user.avatar ? user.avatar : defaultAvatar
                    if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                        this.roles = res.roles;
                        this.permissions = res.permissions;
                    } else {
                        this.roles = ['ROLE_DEFAULT'];
                    }
                    this.name = user.userName;
                    this.avatar = avatar;
                    resolve(res);
                }).catch((error: any) => {
                    reject(error);
                })
            })
        },

        //登出
        Logout() {
            return new Promise<void>((resolve, reject) => {
                logout(this.token).then(() => {
                    this.token = "";
                    this.roles = [];
                    this.permissions = [];
                    localStorage.removeItem('token');
                    resolve();
                }).catch((error: any) => {
                    reject(error);
                })
            })
        }

    },
})

export default user